package cn.com.callback

import cn.com.elite.EliteBean
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiBPHandleWO
 * @Description:宝安排水系统工单数据完单同步接口--外部接口
 * @author: 匡涛 chieh
 * @date 2020-08-19 10:28:00
 *
 */

public class apiBPHandleWO implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(apiBPHandleWO.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");

		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String dataSourceID = "dataSource";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}

		try {
			// 调用处理信息
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());

			String sys_source = GetJV(inObject, "sys_source");
			String sys_flag = GetJV(inObject, "sys_flag");
			String arr_data = GetJV(inObject, "data");

			log.debug("解析信息-sys_source：" + sys_source + " sys_flag：" + sys_flag + " arr_data：" + arr_data);

			if (sys_source == 'YYGL') {
				outData = JTHandle(eliteBean, sys_source, sys_flag, arr_data, dataSourceID);
			}

		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):2\",\"data\":[]}";

		}

		log.debug("名单接入处理完成返回结果:" + outData);

		return outData;
	}

	// 排水工单处理
	public static String JTHandle(EliteBean eliteBean, String sys_source, String sys_flag, String inJson, String dataSourceID) {
		long startTime = System.currentTimeMillis();
		JSONArray arrJsonArray;
		Map<String, String> dealMap = new HashMap<String, String>();
		Map<String, String> dealMsgMap = new HashMap<String, String>();
		JSONArray resArray = new JSONArray();
		String reJson = null;
		try {
			arrJsonArray = new JSONArray(inJson);

			int arrInt = arrJsonArray.length();
			log.debug("接入List数量:" + arrInt);

			for (int i = 0; i < arrInt; i++) {

				log.debug("当前处理数组位置:" + (i + 1));
				JSONObject arrCustJson = arrJsonArray.getJSONObject(i);

				String workorderid = GetJV(arrCustJson, "workorderid");//工单唯一编号
				String handledescription = GetJV(arrCustJson, "handledescription");//处理意见
				String timelimit = GetJV(arrCustJson, "timelimit");//时限-【延期申请】状态必填
				String starttime = GetJV(arrCustJson, "starttime");//开始处理时间
				String finishtime = GetJV(arrCustJson, "finishtime");//处理完成时间

				//申请延时步骤校验
				String dealResult = "";
				String dealMessage = "";
				if (isNull(workorderid) || isNull(handledescription)) {
					dealResult = "0";
					dealMessage = isNullMSG("workorderid", workorderid) + isNullMSG("handledescription", handledescription );
					log.warn("调用参数非空校验异常:" + dealMessage);
					long endTime = System.currentTimeMillis();
				} else {
					//查询现有当前工单编号是否存在现有工单
					def getSelectSQL = eliteBean.chaxun_sql("Select R1.Relation_ID, R3.Handlegroup_ID, R3.Handleby_ID, R3.CurstepStatus, R2.curstep_id_map as Curstep_Id  From TABCCONSULTWORKORDER R1 Left Join Objective R2 On R1.Relation_Id = R2.Objective_Guid Left Join Elitetask R3 On R1.Relation_Id = R3.Objective_Guid Where R2.workorderid= '" + workorderid + "'", dataSourceID);
					log.debug("查询当前同步的工单是否已经存在 SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());

					//获取当前工单编号对应的CRM唯一工单Guid Relation_ID
					String old_Relation_ID = null;
					String old_Handlegroup_ID = null;
					String old_Handleby_ID = null;
					String old_CurstepStatus = null;
					String old_Curstep_Id = null;

					if (getSelectSQL.size() > 0) {
						old_Relation_ID = getSelectSQL.get(0).get("Relation_ID");
						old_Handlegroup_ID = getSelectSQL.get(0).get("Handlegroup_ID");
						old_Handleby_ID = getSelectSQL.get(0).get("Handleby_ID");
						old_CurstepStatus = getSelectSQL.get(0).get("CurstepStatus");
						old_Curstep_Id = getSelectSQL.get(0).get("Curstep_Id");
					} else {
						old_Relation_ID = "";
						old_Handlegroup_ID = "";
						old_Handleby_ID = "";
						old_CurstepStatus = "";
						old_Curstep_Id = "";
					}
					log.debug("查询现有当前工单编号是否存在现有工单-结果old_Relation_ID:" + old_Relation_ID + " old_Handlegroup_ID:" + old_Handlegroup_ID + " old_Handleby_ID:" + old_Handleby_ID + " old_CurstepStatus:" + old_CurstepStatus + " old_Curstep_Id:" + old_Curstep_Id);

					// 提前获取工单的上一步处理人
					def getOldSelectSQL = eliteBean.chaxun_sql("Select R1.Handlegroup, R1.Handleby, R1.From_Stepidmap From Workorderpath3 R1 Left Join (Select Workorder_Guid, Max(Modifieddate) Modifieddate From Workorderpath3 Where To_Stepidmap = 'KNGZL4' And Workorder_Guid = '" + old_Relation_ID + "' Group By Workorder_Guid) R2 On R1.Workorder_Guid = R2.Workorder_Guid And R1.Modifieddate = R2.Modifieddate Where R1.Workorder_Guid = '" + old_Relation_ID + "' And R2.Workorder_Guid Is Not Null", dataSourceID);
					log.debug("查询获取工单的上一步处理人 SQL:" + getOldSelectSQL + " 结果数量:" + getOldSelectSQL.size());

					//获取当前工单编号对应的CRM上一步处理信息
					String before_Handlegroup_ID = null;
					String before_Handleby_ID = null;
					String before_From_Stepidmap = null;

					if (getOldSelectSQL.size() > 0) {
						before_Handlegroup_ID = getOldSelectSQL.get(0).get("Handlegroup");
						before_Handleby_ID = getOldSelectSQL.get(0).get("Handleby");
						before_From_Stepidmap = getOldSelectSQL.get(0).get("From_Stepidmap");
					} else {
						before_Handlegroup_ID = null;
						before_Handleby_ID = null;
						before_From_Stepidmap = null;
					}
					log.debug("提前获取工单的上一步处理人-结果before_Handlegroup_ID:" + before_Handlegroup_ID + " before_Handleby_ID:" + before_Handleby_ID + " before_From_Stepidmap:" + before_From_Stepidmap);


					//此工单存在，且为KNGZL4 运营管理处理节点时候才能改变工单状态
					if (old_Relation_ID != null && old_Relation_ID.length() > 0 && old_Curstep_Id  == "KNGZL4") {
						try {
							//将工单回退到上一步工单处理人 处理节点回退-处理坐席
							if (sys_flag == "back") {
								String[] data1 = new String[6];
								data1[0] = "Insert Into TABCCONSULTWORKORDER_His Select Newid(),* From TABCCONSULTWORKORDER Where Relation_Id = '" + old_Relation_ID + "'";
								data1[1] = "Update TABCCONSULTWORKORDER set workorder_state = 2,r_workingday=datediff( day, '" + starttime + "', '" + finishtime + "' ),r_starttime='" + starttime + "',r_finishtime='" + finishtime + "' Where Relation_Id = '" + old_Relation_ID + "'";
								data1[2] = "Insert Into Workorderstep3 (Workorder_Guid, Workorderstep_Guid, Oldhandleby_Id, Oldhandlegroup_Id, Handleby_Id, Handlegroup_Id, Workorderstepstatus, Comments, Modifieddate, Workorderstepid, Stepexpired, Child_Id, Stepstart, Cur_Expiredflag, Cur_Expiredlen, From_Stepidmap, To_Stepidmap, Workstarttime, Workendtime) Values ('" + old_Relation_ID + "', NewID(), '" + old_Handleby_ID + "', '" + old_Handlegroup_ID + "', '" + before_Handleby_ID + "', '" + before_Handlegroup_ID + "', 'BACK', '" + handledescription + "', Getdate(), Null, Getdate(), Null, Getdate(), 0, 0, '" + old_Curstep_Id + "', 'O70W2B', Getdate(), Getdate())";
								data1[3] = "Delete From Workorderpath3 Where Workorder_Guid = '" + old_Relation_ID + "' And From_Stepidmap = 'O70W2B' And To_stepidmap = '" + old_Curstep_Id + "'";
								data1[4] = "Update Objective Set Handlegroup_Id = '" + before_Handlegroup_ID + "', Handleby_Id = '" + before_Handleby_ID + "',  Map_Id = Map_Id, Curstep_Id_Map = 'O70W2B', Modifiedby = 'SELITE', Modifieddate = Getdate(),comments='" + handledescription + "',branch_endtime=GETDATE() Where Objective_Guid = '" + old_Relation_ID + "'";
								data1[5] = "Update Elitetask Set Handlegroup_Id = '" + before_Handlegroup_ID + "', Handleby_Id = '" + before_Handleby_ID + "', Map_Id = Map_Id, Curstep_Id = 'O70W2B', Curstep_Id_Map = 'O70W2B',  Modifiedby = 'SELITE', Modifieddate = Getdate(),comments='"+handledescription+"' Where Objective_Guid = '" + old_Relation_ID + "'";
								log.debug("判断处理工单回退状态进行下一步处理SQL:" + data1.toString());
								int[] dataresult1 = eliteBean.updateBatch(data1, dataSourceID);
								log.debug("判断处理工单回退状态进行下一步处理SQL结果:" + dataresult1.toString());

								Boolean arrImg = GetJV(arrCustJson, "arrImg")
								log.debug("arrImg:	"+arrImg);
								if (arrImg==true) {
									//获取附件信息
									JSONArray arrImgJsonArray = arrCustJson.getJSONArray("arrImg");
									log.debug("arrImgJsonArray:	"+arrImgJsonArray );
									String arrImgpath = "";
									String arrImgname = "";
									if(old_Relation_ID != null || old_Relation_ID.length() > 0) {
										for (int j = 0; j < arrImgJsonArray.length(); j++) {
											JSONObject arrImgJson = arrImgJsonArray.getJSONObject(j);
											arrImgpath = GetJV(arrImgJson, "path");
											arrImgname = GetJV(arrImgJson, "name");
											def aaa=eliteBean.update("insert into rm_uploadrecord(guid,objectiveID,path,name,operator,operationtime,filedesc,type)VALUES(NEWID(),'" + old_Relation_ID + "','" + arrImgpath + "','" + arrImgname + "','运营管理系统',GETDATE(),'','4')", "dataSource");
										}
									}
								}
								dealMessage="当前处理状态回退处理成功";
							}

							// 延期申请,将工单状态变更为延期申请，更新延期申请时间的操作暂定由坐席去修改,CRM只在历史步骤提示处理意见内容
							if (sys_flag == "apply" ) {
								handledescription='延期时限：'+timelimit+','+handledescription;
								String[] data1=new String[5];
								data1[0] = "Insert Into TABCCONSULTWORKORDER_His Select Newid(),* From TABCCONSULTWORKORDER Where Relation_Id = '" + old_Relation_ID + "'";
								data1[1] = "Update TABCCONSULTWORKORDER set workorder_state = 3,r_workingday=datediff( day, '" + starttime + "', '" + finishtime + "' ),r_starttime='" + starttime + "',r_finishtime='" + finishtime + "' Where Relation_Id = '" + old_Relation_ID + "'";
								data1[2] = "Insert Into Workorderstep3 (Workorder_Guid, Workorderstep_Guid, Oldhandleby_Id, Oldhandlegroup_Id, Handleby_Id, Handlegroup_Id, Workorderstepstatus, Comments, Modifieddate, Workorderstepid, Stepexpired, Child_Id, Stepstart, Cur_Expiredflag, Cur_Expiredlen, From_Stepidmap, To_Stepidmap, Workstarttime, Workendtime)  Values ('" + old_Relation_ID + "', NewID(), '"+old_Handleby_ID+"', '"+old_Handlegroup_ID+"', '" + before_Handleby_ID + "', '" + before_Handlegroup_ID + "', 'APPLY', '"+handledescription+"', Getdate(), Null, Getdate(), Null, Getdate(), 0, 0, '"+old_Curstep_Id+"', '" + before_From_Stepidmap + "', Getdate(), Getdate())";
								data1[3] = "Update Objective Set Handlegroup_Id = '" + before_Handlegroup_ID + "', Handleby_Id = 'O70W2B', Map_Id = Map_Id, Modifiedby = 'SELITE', Modifieddate = Getdate() ,comments='"+handledescription+"'  Where Objective_Guid = '" + old_Relation_ID + "'";
								data1[4] = "Update Elitetask Set Handlegroup_Id = '" + before_Handlegroup_ID + "', Handleby_Id = '" + before_Handleby_ID + "', Map_Id = Map_Id, Curstep_Id = 'O70W2B', Objectivesubstatus = Objectivesubstatus, Modifiedby = 'SELITE', Modifieddate = Getdate(),comments='"+handledescription+"' Where Objective_Guid = '" + old_Relation_ID + "'";
								log.debug("判断处理工单延期状态进行下一步处理SQL:" + data1.toString());
								int[] dataresult1 = eliteBean.updateBatch(data1, dataSourceID);
								log.debug("判断处理工单延期状态进行下一步处理SQL结果:" + dataresult1.toString());
								dealMessage="当前处理状态延期处理成功";
							}

							dealResult = "1";
						} catch (Exception e) {
							dealResult = "0";
							dealMessage = "当前处理状态变更的工单整体处理SQL异常";
							log.error(dealMessage + ":" + e.getMessage());
						}

					}else {
						long endTime = System.currentTimeMillis();
						dealResult = "0";
						dealMessage = "当前处理结果变更的工单在CRM系统不存在ID或工单步骤不在处理节点";
						log.warn(dealMessage + ":" + workorderid);
						reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + dealMessage + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
					}
				}
				dealMap.put(workorderid, dealResult);
				dealMsgMap.put(workorderid, dealMessage);
			}

			// 将每条处理结果转换为JSONArray
			int j = 0;
			for (Map.Entry<String, String> m : dealMap.entrySet()) {
				JSONObject resObject = new JSONObject();
				resObject.put("id", m.getKey());
				resObject.put("code", m.getValue());
				resObject.put("message", dealMsgMap.get(m.getKey()).toString());
				resArray.put(j, resObject);
				j++;
			}
			log.debug(resArray.toString());
			long endTime = System.currentTimeMillis();
			// 包装拼接返回JSONObject
			reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"处理完成、调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray.toString() + "}";

		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
		}

		return reJson;
	}


	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		log.debug("解析-k=" + getKey + " v=" + Rev_Value);
		return Rev_Value;
	}

	// 非空校验isNull
	public static boolean isNull(String value) {

		boolean reFlag = true;
		if (value == "" || value.length() <= 0) {
			reFlag = true;
		} else {
			reFlag = false;
		}

		return reFlag;
	}

	// 非空校验isNullMSG
	public static String isNullMSG(String key, String value) {

		String reResult = "";
		if (value == "" || value.length() <= 0) {
			reResult = key + "必填字段;";
		}
		return reResult;
	}

}